import { ReactiveEffect } from "./effect"

class ComputedRefImpl {
    private _getter: any
    private _dirty: boolean = true
    private _value: any
    private _effect: ReactiveEffect
    constructor(getter) {
        this._getter = getter
        
        // 当依赖的响应式对象的值发生改变的时候，要去解锁
        // 当有 scheduler 就会执行 scheduler ，不会执行 getter
        this._effect = new ReactiveEffect(getter, () => {
            if (!this._dirty) {
                this._dirty = true
            }
        })
    }

    get value() {
        // 缓存 -> 上锁
        if (this._dirty) {
            this._dirty = false
            this._value = this._effect.run()
        }
                
        return this._value
    }
}

export function computed(getter) {
    return new ComputedRefImpl(getter)
}